package com.plian.system.service.sys.per;

import com.plian.Tools.Tools;
import com.plian.Tools.TreeUtli;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dao.sys.per.UserOrgDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.sys.orgzation.OrgzationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 权限配置
 */
@Slf4j
@Service
public class UserOrgService {
    @Autowired
    UserOrgDao userOrgDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    OrgzationService orgzationService;
    @Autowired
    UserDao userDao;

    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 选择当前账号下，权限单位树结构
     * @param pd
     * @return
     * @throws Exception
     */
    public ObjResult UserOrg(PageData pd)  {
        ObjResult objResult;
        String userId=pd.getString("userId");
        try {
            List<PageData> list= userOrgDao.queryUserOrg(userId);
            List<PageData> orgAll=orgzationDao.list(pd);
            //循环将有权限的标识
            orgAll.forEach(pageData -> {
                pageData.put("check",false);
                list.forEach(p ->{
                    if(pageData.getString("id").equals(p.getString("orgId"))){
                        pageData.put("check",true);
                    }
                });
            });
            TreeUtli treeUtli=new TreeUtli();
            List<PageData> l=treeUtli.getChlid("0",orgAll);
            objResult=new ObjResult(CommonCode.SUCCESS);
            PageData p=new PageData();
            p.put("userId",userId);
            p.put("list",l);
            objResult.setPageData(p);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    /**
     * 配置账号，单位
     * @return
     */
    @Transactional(rollbackFor=RuntimeException.class)
    public ObjResult userOrgConfig(PageData pd){
        try {
            saveUserOrg(pd);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }

    }


    public void saveUserOrg(PageData pd) throws Exception {
        List<String> ids= (List<String>) pd.get("orgIds");
        String userId=pd.getString("userId");
        List<PageData> list=new ArrayList<>();
        ObjResult objResult;
        if(ids==null||ids.size()<=0){
            userOrgDao.del_orgUser(userId);
        }

        //查询当前账号下的单位
        List<PageData> l= userOrgDao.queryUserOrg(userId);
        //得到不需要操作的列表
        List<String> l1= new ArrayList<>();
        //所有权限的orgid
        List<String> l2= new ArrayList<>();
        List<String> l3= new ArrayList<>();

        if(l!=null&&l.size()>0){
            l.forEach(pageData -> {
                ids.forEach(s -> {
                    if(s.equals(pageData.getString("orgId"))){
                        l1.add(pageData.getString("userOrgId"));
                    }
                    l2.add(pageData.getString("userOrgId"));
                    l3.add(pageData.getString("orgId"));
                });
            });

            l.clear();
            //得到需要删除的列表,权限有,传来的id没有
            l2.removeAll(l1);
            //需要保存的列表,权限没有，传来的id有
            ids.removeAll(l3);
            l1.clear();
            l3.clear();
        }
        ids.forEach(s -> {
            PageData p=new PageData();
            p.put("userId",userId);
            p.put("id", UuidUtil.get32UUID());
            p.put("orgId",s);
            list.add(p);
        });
        //批量删除
        if(l2!=null && l2.size()>0){
            userOrgDao.del_ids(l2);
        }
        //批量保存
        if(list!=null && list.size()>0){
            userOrgDao.userOrgConfig(list);
        }
        PageData userPd = userDao.findbyid(userId);
    }


    public ListResult getUserByOrgId(PageData pd){
        String orgId=pd.getString("orgId");
        try {
            PageData org=orgzationDao.findbyid(orgId);
            List<PageData> list=new ArrayList<>();
            if (org.getInteger("type")==4) {
                list=userDao.getUsersUnderGZW();
            }else{
                Page page = new Page(false, pd);
                pd.put("orgIds", Arrays.asList(orgId));
                String keyword = pd.getString("keyword");
                if (Tools.notEmpty(keyword)) {
                    keyword = keyword.replaceAll("_", "/_");
                    pd.put("keyword", keyword.trim());
                }
                list= userDao.listByCreatUser(page);
            }
            ListResult Result = new ListResult<>(CommonCode.SUCCESS);
            Result.setList(list);
            return Result;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }

    }
}
